package com.yinhai.message.implement.dwr.controller;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;

import com.yinhai.message.api.util.MessageType;
import com.yinhai.message.implement.dwr.listener.DWRScriptSessionListener;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.io.FileTransfer;
import org.springframework.stereotype.Controller;

import com.yinhai.core.common.api.config.impl.SysConfig;
import com.yinhai.message.api.bean.TMUser;
import com.yinhai.message.core.po.MessageFilePo;
import com.yinhai.message.core.util.FTPUtils;
import com.yinhai.message.core.util.IMessageConstant;
import com.yinhai.message.search.bpo.IMessageSearchBpo;
import com.yinhai.message.search.vo.MessageInfoVo;

/**
 * @author maxp
 * @Create 2017-01-04-16:48
 */
@Controller
@RemoteProxy(name="dwrController")
public class DWRController {      
    
	@Resource
	private IMessageSearchBpo messageSearchBpo;
    /**
     * 页面初始化的时候，存放userid到ScriptSeession里面
     * @param userid
     */
    @RemoteMethod
    public void onPageLoad(String systemid,String userid,String pageid){
        ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
        scriptSession.setAttribute("systemid",systemid);
        scriptSession.setAttribute("userid",userid);
        scriptSession.setAttribute("pageid",pageid);
        try {
			for (Iterator<Map.Entry<String, ScriptSession>> it = DWRScriptSessionListener.scriptSessionMap.entrySet().iterator(); it.hasNext(); ) {
				Map.Entry<String, ScriptSession> item = it.next();
				ScriptSession sc = item.getValue();
				if (sc.isInvalidated()) {
					it.remove();
				}
			}
		}catch (Exception e){

		}
    }
    
    @RemoteMethod
  	public Object queryMessage(String systemid,String userid,String pageid) throws Exception {
    	return queryMessage(systemid,userid,pageid,0);
    }
    @RemoteMethod
  	public Object queryMessage(String systemid,String userid,String pageid,int num) throws Exception {
    	TMUser user = new TMUser();
    	user.setAppId(systemid);
    	user.setUserId(userid);
    	List<MessageInfoVo> listVo = messageSearchBpo.getMessage(systemid, userid,pageid, num, MessageType.DWR);
    	List<Map<String,String>> listMap = new ArrayList<>();
    	for(MessageInfoVo vo :listVo){
    		StringBuilder fileStr = new StringBuilder("附件：<br>");
    		if("file".equals(vo.getSelfType())){
    			List<MessageFilePo> listFilePo = messageSearchBpo.getMessageFile(vo.getMgid());
        		for(MessageFilePo filePo:listFilePo){
        			fileStr.append(filePo.getFilename())
        				   .append(":<a id='")
        				   .append(filePo.getId())
        				   .append("' href='javascript:mgAtmDownload(")
        				   .append(filePo.getId())
        				   .append(")' style='color: #1A5E9E;cursor: pointer'>下载</a>")
        				   .append("<br>");
        		}
    		}
    	
    		Map<String,String> msg = new HashMap<>();
			msg.put("mgid", vo.getMgid());
			msg.put("title", vo.getTitle());
			msg.put("content", vo.getContent());
			msg.put("attachment", fileStr.toString());
			msg.put("mgdateShow", vo.getMgdateShow());
			msg.put("suserid", vo.getSuserid());
			msg.put("sname", vo.getSname());
			msg.put("read", vo.getRead());
			msg.put("selfType", vo.getSelfType());
			msg.put("otherData1", vo.getOtherData1());
			msg.put("otherData2", vo.getOtherData2());
			msg.put("otherData3", vo.getOtherData3());
			listMap.add(msg);
    	}
//    	SendMessageAutoUtil.sendMessageAuto(user, listMap, "dealAllMessage");
    	return listMap;
  	}
    
    @RemoteMethod
   	public void readMessage(String mgid,String systemid,String userid) throws Exception {
    	messageSearchBpo.setMessageRead(mgid, systemid, userid,MessageType.DWR);
   	}
    @RemoteMethod
   	public FileTransfer  downloadFile(String fileid) throws Exception {
    	MessageFilePo po = messageSearchBpo.getMessageFileByid(fileid);
    	if(po!=null){
        	String storeMode = po.getFilestoremode();
        	String mimetype = new MimetypesFileTypeMap().getContentType(po.getFilename());
        	
        	InputStream ins =null;
        	if(IMessageConstant.MSG_FILE_STORE_LOCAL.equals(storeMode)){
        		ins = new FileInputStream(po.getFilepath()); 
        	}else if (IMessageConstant.MSG_FILE_STORE_FTPSERVER.equals(storeMode)) {
        		FTPUtils ftpUtils = FTPUtils.getInstance();
				String serverName = SysConfig.getSysConfig("msgFileStorePlace");
				ins = ftpUtils.retrieveFile(serverName, po.getFilepath(), new String(po.getFilename().getBytes("GBK"),"iso-8859-1"));
            } else if (IMessageConstant.MSG_FILE_STORE_UNIFIED_STORE.equals(storeMode)) {

            }
        	return new FileTransfer(java.net.URLEncoder.encode(po.getFilename(),"utf-8"),mimetype,ins);
    	}
    	return null;
   	}
}
